// pages/buy/buy.js
var utils = require('../../utils/util');

Page({
  gotoPage: utils.gotoPage,

  /**
   * 页面的初始数据
   */
  data: {
    number: 1,
    totalamt: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var pid = that.options.pid;
    var gid = that.options.gid;
    var HOST = getApp().globalData.HOST;

    var product = wx.getStorageSync('product');
    console.log('product', product);

    that.setData({
      product: product,
      totalamt: '' + parseFloat(product.price).toFixed(2),
      pid: pid,
      gid: gid
    });

  },

  // +/- 数量
  changeNumber: function(event) {
    var that = this;
    var v = event.currentTarget.dataset.v;
    console.log('v', v);

    var number = that.data.number + parseInt(v);
    number = number <= 0 ? 1 : number;
    var totalamt = parseFloat(that.data.product.price) * number;

    that.setData({
      number: number,
      totalamt: '' + totalamt.toFixed(2)
    });
  },

  // 编辑地址
  editAddress: function(event) {
    console.log(event.currentTarget.dataset.id);
    var id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/usercenter/addressnew/addressnew?id=' + id,
    });
  },

  // 添加留言
  inputNote: function(event) {
    var notes = event.detail.value;
    this.setData({
      notes: notes
    });
  },

  // 提交订单, 并调起微信支付
  submitOrder: function() {
    var that = this;
    var HOST = getApp().globalData.HOST;
    var openid = wx.getStorageSync('openid');

    var pid = this.data.pid;
    var gid = this.data.gid;
    var price = this.data.product.price;
    var number = this.data.number;
    var totalamt = this.data.totalamt;
    var address = this.data.address;
    var notes = this.data.notes;

    if (!address) {
      wx.showToast({
        title: '请添加收获地址',
        icon: 'none'
      });
      return false;
    }

    var data = {
      openid: openid,
      productid: pid, //TODO
      groupbuyid: gid, //TODO
      number: number,
      price: price,
      totalamt: totalamt,
      addressid: address.id,
      notes: notes
    }
    console.log('order data:', data);

    // 提交订单, 统一下单
    wx.request({
      // url: HOST + 'appwechatorder',
      url: HOST + 'group/buy/order',
      method: 'post',
      data: data,
      success: function(resp) {
        console.log('下单:', resp)
        // 调起微信支付接口 TODO
        // https://developers.weixin.qq.com/miniprogram/dev/api/wx.requestPayment.html
        if (1)
          wx.requestPayment({
            timeStamp: resp.data.data.timestamp, // timeStamp  string    是  时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
            nonceStr: resp.data.data.noncestr, // nonceStr  string    是  随机字符串，长度为32个字符以下
            package: 'prepayid='+resp.data.data.prepayid, // package  string    是  统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
            paySign: resp.data.data.sign, // paySign  string    是  签名，具体签名方案参见 小程序支付接口文档
            signType: 'MD5', // signType  string  MD5  否  签名算法
            success: function(resp) {
              console.log('微信支付结果:', resp);
            },
            fail: function(resp) {
              console.log('微信支付失败:', resp);
            },
            complete: function(resp) {
              // 支付, 进入我的订单页
              wx.navigateTo({
                url: '/pages/usercenter/myorder/myorder',
              });
            },
          }); // 微信支付
      },
      fail: function(resp) {

      },
      complete: function(resp) {

      }
    }) // 统一下单
  },

  // 选择收货地址
  selectAddress: function(event) {
    wx.navigateTo({
      url: '/pages/usercenter/addresslist/addresslist?from_order=1',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var address = wx.getStorageSync('address');
    this.setData({
      address: address
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log('buy page onUnload...');
    wx.removeStorageSync('from_order');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var pid = this.data.pid;
    var gid = this.data.gid;
    return {
      title: '国学小书童',
      path: '/pages/home/home?pid=' + pid + '&gid=' + gid,
      imageUrl: '/images/g1.jpg',
    }
  }
})